import { Component, OnInit } from '@angular/core';
import { JsonApiService } from "app/core/api/json-api.service"; //http请求配置引入
import { Router, ActivatedRoute } from "@angular/router"; //路由引入
import { config} from '../../shared/smartadmin.config';

declare var $: any;
@Component({
	selector: 'sa-device-fault',
	templateUrl: './device-fault.component.html'
})
export class DeviceFaultComponent implements OnInit {
	tableData = []; //table数据
	totalCount:number = 0; //分页总条数
	curPage:number = 1; //分页当前页
	pageSize:number = 10; //内置的分页每页条数
	searchKey:string = ''; //搜索keyword
	faultTypeName:string = '';//查询故障类型参数
	repairedStatus:string = '';//查询故障状态参数
	selectedCompanyName:string = '';//查询公司参数
	selectedCompanyId:string = '';//查询公司参数
	deviceId:string = '';//查询设备参数
	carNumber:string = '';//查询车牌号码参数
	userList:any = [];//用户数据List
	userName:string = '';//查询用户参数
	userId:string = '';//查询用户id参数
	startTime = '';//查询开始时间参数
	endTime ='';//查询结束时间参数
	dateType:string = '1';//时间类型
	sortType: string = '2';
	isPush:string='2'
	faultTypeArr:any=[{
		'type':1,
		'text':'传感器'
	},{
		'type':2,
		'text':'GPS'
	},{
		'type':3,
		'text':'线材'
	},{
		'type':4,
		'text':'主机'
	},{
		'type':5,
		'text':'其他'
	}]

	isPushTypeArr:any=[
	{
		'type':0,
		'text':'不限制'
	},{
		'type':1,
		'text':'限制'
	}]
	waitingRepairCarTopList:any = [];//待维修统计排名
	topNumber:string = '10';//默认top10
	curBtn:string = '';//排名高亮按钮;默认一周
	topTimeID:any ={
		picker1:'datetimepicker5',
		picker2:'datetimepicker6'
	};//排名试驾元素ID
	topStartTime:string = '';//排名开始时间
	topEndTime:string = '';//排名结束时间
	modal:any = { //图片弹窗
		picture:'',
		active:'',   //激活的图片
		activeNum:null,  //激活的图片下标
	};
	inputCompanyTreeCarData:any = {};//车辆运行状态模块跳转该页面传递过来的参数
	constructor(private jsonApiService: JsonApiService, private router: Router,private activatedRoute: ActivatedRoute) {
		activatedRoute.queryParams.subscribe(queryParams => {
			this.curPage = queryParams.nowPage == undefined? 1:queryParams.nowPage;
			this.inputCompanyTreeCarData = JSON.parse(common.getCookie('jumpRepairedDeviceList'));
		});
	}

	ngOnInit() {
		this.initBtn()
		this.initAllUser().then(()=>{
			this.selectUserName();
		});
		this.initDate();
		this.load();
	}
	btnData: any = []
	resourceExport: boolean = false //导出按钮权限
	factoryLimit:boolean = false //查看进出厂限制
	//初始化权限按钮
  initBtn() {
    this.btnData = JSON.parse(decodeURIComponent(localStorage.getItem('cargpsw_device:management:fault')))
	console.log('btnData', this.btnData)
    if (!this.btnData) {
      return
    }
    for (let item of this.btnData) {
      if (item.sourceKey === 'deviceFault:export' && item.parentId) {
        this.resourceExport = true
      }
    }

	for (let item of this.btnData) {
		if (item.sourceKey === 'deviceFault:enterFactoryLimit' && item.parentId) {
		  this.factoryLimit = true
		}
	}
  }
	ngOnDestroy(){
		document.onclick = null;
	}
	topDateSelect(type){
		this.curBtn = type;
		let curTime = new Date();
		let curDate = common.getTimeDay(curTime);
		let currentMonthDays = new Date().getDate()-1;
		let startTime, endTime;
		switch(type) {
			case '1':
				this.startTime = curDate + ' 00:00:00';
				this.endTime = curDate + ' 23:59:59';
				break;
			case '2':
				this.startTime = common.getTimeDay(new Date(curTime.getTime() - 3600 * 24 * 1000 * 6)) + ' 00:00:00';
				this.endTime = curDate + ' 23:59:59';
				break;
			case '3':
				this.startTime = common.getTimeDay(new Date(curTime.getTime() - 3600 * 24 * 1000 * currentMonthDays)) + ' 00:00:00';
				this.endTime = curDate + ' 23:59:59';
				break;
			default:
				this.startTime = '';
				this.endTime = '';
				break;
		}
		$('#datetimepicker5').val(this.startTime).change();
		$('#datetimepicker6').val(this.endTime).change();
		this.initCarWaitingRepairTop();
	}
	//关闭待维修车辆Top弹窗
	waitingRepairClose(modal){
		modal.hide();
	}
	//待维修车辆Top排名
	carWaitingRepairTop(modal){
		modal.show();
		this.curBtn = '';
		this.topNumber = '10';
		this.initCarWaitingRepairTop();
	}
	// 数据导出
	exportData(){
		let data = {
			pageSize:this.pageSize,
			nowPage:this.curPage,
			parameters:{
				dateType:this.dateType,
				sortType:this.sortType,
				searchKey:this.searchKey,
				companyId:this.selectedCompanyId,
				deviceId:this.deviceId,
				// userName:this.userName,
				faultTypeName:this.faultTypeName,
				repairedStatus:this.repairedStatus,
				startDate:this.startTime,
				endDate:this.endTime,
				isPush:this.isPush,		//是否推送
				isByAuth:true,
				isExport: true
			}
		}
		
		common.exprotDataFile(data, 'gridPager', config.BaseURL + 'deviceRepaired/findDeviceRepairedList.html')
	}
	//排名回调
	topNumberChange(){
		this.initCarWaitingRepairTop();
	}
	//待维修车辆Top排名数据拉取
	initCarWaitingRepairTop(){
		let data = {
			searchKey:this.searchKey,
			companyId:this.selectedCompanyId,
			deviceId:this.deviceId,
			userName:this.userName,
			faultTypeName:this.faultTypeName,
			repairedStatus:this.repairedStatus,
			startDate:this.startTime,
			endDate:this.endTime,
			isPush:this.isPush,		//是否推送
			isByAuth:true
		}
		let reqdata = 'param='+JSON.stringify(data)+"&topNumber="+this.topNumber;
		this.jsonApiService.http("deviceRepaired/countDataRecordForTop.html",reqdata).subscribe(result => {
			if(result.data&&result.success){
				this.waitingRepairCarTopList = [];
				let temArr:any = result.data;
				for(let key in temArr){
					let obj = {
						text:key,
						value:temArr[key]
					}
					this.waitingRepairCarTopList.push(obj);
				}
			}
		})
	}
	//初始化时间
	initDate(){
		var that = this;
		return new Promise(function (resolve, reject) {
			System.import('assets/js/datepicker/js/bootstrap-datetimepicker.min.js').then(
				()=>{
					System.import('assets/js/datepicker/locales/bootstrap-datetimepicker.zh-CN.js').then(()=>{
						$("#datetimepicker1").datetimepicker({
							format: "yyyy-mm-dd hh:ii:ss",
						    language: "zh-CN",
						    autoclose: true,
						}).on("changeDate", function(e){
							var date = e.date;
							var time = common.getTimeMmss(date);
							$("#datetimepicker2").datetimepicker("setStartDate", time);
						});
						$("#datetimepicker2").datetimepicker({
							format: "yyyy-mm-dd hh:ii:ss",
						    language: "zh-CN",
						    autoclose: true,
						}).on("changeDate", function(e){
							var date = e.date;
							var time = common.getTimeMmss(date);
							$("#datetimepicker1").datetimepicker("setEndDate", time);
						});
						resolve();
					});
				}
			);
		})
	}
	//删除所选时间
	del_date(){
		this.startTime = '';
		this.endTime ='';
		$('#datetimepicker1').val('').change();
		$('#datetimepicker2').val('').change();
		$("#datetimepicker2").datetimepicker("setStartDate", null);
		$("#datetimepicker1").datetimepicker("setEndDate", null);
	}
	//擦除用户所选值
	delUserName(){
		this.userName = '';
		this.userId = '';
		//采用简单粗暴的方法清除;官方推荐的方法失效
		var str=$("<span class='select2-selection__placeholder'>请选择</span>");
		$('#userNameSelect2').val("");
		$("#select2-userNameSelect2-container").empty();
		$("#select2-userNameSelect2-container").attr("title","");
		$("#select2-userNameSelect2-container").prepend(str);
	}
	//初始化select2 选项
	selectUserName(){
		var that = this;
		System.import('script-loader!select2/dist/js/select2.min.js').then(()=>{
			System.import('assets/js/select2-zh-CN.js').then(()=>{
				$("#userNameSelect2").select2({
			    	language : "zh-CN",
			    	placeholder :"请选择",
			    	allowClear : true,
			    	data : this.userList,//为Select添加数据
			        templateResult: this.formatRepo
			    }).on ("select2:select", function (e){
	        	  	var data = e.params.data;
	        	  	that.userName = data.text;
	        	  	that.userId = data.id;
		        });
			})
		})
	}
	//select2 格式回调函数
	formatRepo (state) {
		if (!state.id) {return state.text};
		var $state = $('<span><i class="fa fa-user green"></i>&nbsp;&nbsp;' + state.text + '</span>');
		return $state;
	}
	//拉取
	initAllUser(){
		var that = this;
		return new Promise(function (resolve, reject) {
			that.jsonApiService.http("user/getAllUserList.html",null).subscribe(data=> {
				if(data.success){
					var userList = data.data;
		        	var selectdata = [];
		        	for(var i = 0 ; i < userList.length ; i++) {
		        		var obj = {
		        			id:userList[i].id,
		        			text:userList[i].name,
		        		}
		        		selectdata[i] = obj;
		        	}
				}
				that.userList = selectdata;
				resolve();
			})
		})
	}
	//table刷新
	refresh(){
    	this.load();
   }
	//表格搜索
	table_search() {
		this.curPage=1;
		this.searchKey = common.stringTrim(this.searchKey);
		this.load();
	}
	//初始化加载list数据
	load() {
		this.startTime = $('#datetimepicker1').val();
		this.endTime = $('#datetimepicker2').val();
		let data = {
			pageSize:this.pageSize,
			nowPage:this.curPage,
			parameters:{
				dateType:this.dateType,
				sortType:this.sortType,
				searchKey:this.searchKey,
				companyId:this.selectedCompanyId,
				deviceId:this.deviceId,
				// userName:this.userName,
				faultTypeName:this.faultTypeName,
				repairedStatus:this.repairedStatus,
				startDate:this.startTime,
				endDate:this.endTime,
				isPush:this.isPush,		//是否推送
				isByAuth:true,
				isExport: false
			}
		}
		let reqdata = 'gridPager='+JSON.stringify(data);
		
		this.jsonApiService.http("deviceRepaired/findDeviceRepairedList.html", reqdata).subscribe(result => {
			this.tableData = result.exhibitDatas||[];						
			this.tableData.map(item=>item.callDuration = common.secondToDate(item.callDuration));				
			this.totalCount = result.recordCount;
		})
	}
	//分页回调
	paginate(e){
		this.curPage = e.page+1;
		this.pageSize = e.rows;
		this.load();
	}

	//公司选中回调
	companySelected(data){
		this.selectedCompanyId = data.companyId;
		this.selectedCompanyName = data.companyName;
		this.deviceId = data.deviceId;
		this.carNumber = data.carNumber;
	}
	//查看照片
	open_img(row,val){
		val.show();
		if(row.paths.length > 0){
			this.modal.active = row.paths[0];
			this.modal.activeNum = 0;
			this.modal.picture = row.paths;
		}
	}
	//图片hover事件
	switch_img(index){
		this.modal.activeNum = index;
		this.modal.active = this.modal.picture[index];
	}
	//pre
	change_img_left(){
		if(this.modal.activeNum){
			this.modal.activeNum--;
			this.modal.active = this.modal.picture[this.modal.activeNum];
		}
	}
	//next
	change_img_right(e){
		if(this.modal.activeNum < this.modal.picture.length-1){
			this.modal.activeNum++;
			this.modal.active = this.modal.picture[this.modal.activeNum];
		}
	}
	//关闭图片弹窗
	imgClose(val){
		val.hide();
	}
}